package com.javen.utils;

import com.javen.sdk.AccessTokenApi;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.AccessToken;
import com.jfinal.weixin.sdk.api.ApiConfig;

import java.util.List;

/**
 * 项目启动后加载所有微信公众号的token
 * Created by Administrator on 2017/9/13 0013.
 */
public class RefreshToken {
    public  void RefreshToken(){
        try {
            Cache cache= Redis.use("weixinConfig");
            String sql="select originalID from weixin_public_account_info WHERE organizationId is not NULL group by originalID";
            List<Record> recordList= Db.find(sql);
            for (int i=0;i<recordList.size();i++){
                Record record=recordList.get(i);
                String originalID=record.getStr("originalID");
                Record accountInfo = Db.findFirst("select * from weixin_public_account_info where originalID = ?", originalID);
                int id=accountInfo.getInt("id");
                String appID=accountInfo.getStr("appID");
                String appsecret=accountInfo.getStr("appsecret");
                ApiConfig apiConfig=new ApiConfig();
                apiConfig.setAppId(appID);
                apiConfig.setAppSecret(appsecret);
//                apiConfig.setOriginalID(originalID);
                AccessToken accessToken=null;
                String token="";
                try {
                    accessToken= AccessTokenApi.refreshAccessToken(apiConfig);
                    token=accessToken.getAccessToken();
                }catch (Exception e){
                    Syslog.error(appID+"  获取token异常"+e);
                }
                List<Record> records = Db.find("select * from weixin_public_account_info where originalID = ?", originalID);
                Syslog.info("appId："+appID+"获取到的token ::"+token);
                for (Record r:records){
                    r.set("token",token);
                    cache.set(appID,r);
                    cache.set(id,r);
                    cache.set(originalID,r);
                    cache.set(r.getStr("organizationId"),r);
                    //todo key == originalID or macId ?
                }
            }
        }catch (Exception e){
                Syslog.error("获取微信Token异常::"+e);
        }

    }
}
